<script setup lang="ts">

import {ArrowRight, Delete, Edit, Search} from "@element-plus/icons-vue";
import {ref, reactive, onMounted} from "vue";
import myAxios from "../service/my-axios.ts";
import {ElMessage, ElMessageBox, FormRules} from "element-plus";


const searchGroupname = ref('')
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(0)
const total = ref(0)
const addGroupFormVisible = ref(false)
const formLabelWidth = '140px'
const updateGroupFormVisible = ref(false)

onMounted(async () => {
  await handleSearch()
})
const handleSearch = async () => {
  tableData.value = []
  currentPage.value = 1
  let res = await myAxios.get("/team/search?name=" + searchGroupname.value + "&currentPage=" + currentPage.value);
  if (res?.data.code === 0) {
    res.data.data.records.forEach(group => {
      if(group.status == 0)
        group.status = '公开'
      else if(group.status == 1)
        group.status = '私密'
      else if(group.status == 2)
        group.status = '加密'
      tableData.value.push(group)
    })
    currentPage.value = res.data.data.current
    pageSize.value = res.data.data.size
    total.value = res.data.data.total
  }
}

const getGroupInfo = async (id: string) => {
  let res = await myAxios.get("/team/" + id);
  if (res.data.code === 0) {
    updateGroupFormVisible.value = true
    updateGroupForm.value = res.data.data
    if(res.data.data.status == 0)
      updateGroupForm.value.status = '公开'
    else if(res.data.data.status == 1)
      updateGroupForm.value.status = '私密'
    else if(res.data.data.status == 2)
      updateGroupForm.value.status = '加密'
  } else {
    ElMessage.error(res.data.description)
  }
}
const confirmDelete = (id: string) => {
  ElMessageBox.confirm(
      '此操作无法撤销',
      '确认删除?',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const res = await myAxios.post("/team/delete", {
          id
        })
        if (res.data.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          await handleSearch()
        } else {
          ElMessage.error(res.data.description)
        }
      })
}
const handleCurrentChange = async (val: number) => {
  tableData.value = []
  const url = "/team/search?name=" + searchGroupname.value + "&currentPage=" + val
  let res = await myAxios.get(url);
  if (res?.data.code === 0) {
    res.data.data.records.forEach(group => {
      if(group.status == 0)
        group.status = '公开'
      else if(group.status == 1)
        group.status = '私密'
      else if(group.status == 2)
        group.status = '加密'
      tableData.value.push(group)
    })
    currentPage.value = res.data.data.current
    pageSize.value = res.data.data.size
    total.value = res.data.data.total
  }
}

const initFormData = {
  "name": "",
  "description": "",
  "expireTime": "",
  "maxNum": 1,
  "password": "",
  "status": "0",
}
const addTeamData = ref({...initFormData})
interface RuleForm {
  name: string,
  maxNum: bigint,
}
const addGroupFormRoles = reactive<FormRules<RuleForm>>({
  name: [
    {required: true, message: '请输入群名', trigger: 'blur'}
  ],
  maxNum: [
    {required: true, message: '请输入最大人数', trigger: 'blur'}
  ]
})
const handleAddGroup = async () => {
  const postData = {
    ...addTeamData.value,
    status: Number(addTeamData.value.status),
  }
  let res = await myAxios.post("/team/admin/add", postData);
  if (res.data.code === 0) {
    ElMessage({
      message: '交流群添加成功,ID为' + res.data.data,
      type: 'success',
    })
    addGroupFormVisible.value = false
    await handleSearch()
  } else {
    ElMessage.error(res.data.description)
  }
}
const updateGroupForm = ref({
  id: '',
  name: '',
  description: '',
  maxNum: '',
  expireTime: '',
  userId: '',
  status: ''
})
const ValueOption = [
  {
    label: '公开',
    value: '0'
  },
  {
    label: '私有',
    value: '1'
  },
  {
    label: '加密',
    value: '2'
  },
]
const handleUpdateGroup = async () => {
  const GroupData = {
    id: updateGroupForm.value.id,
    name: updateGroupForm.value.name,
    description: updateGroupForm.value.description,
    maxNum: updateGroupForm.value.maxNum,
    expireTime: updateGroupForm.value.expireTime,
    userId: updateGroupForm.value.userId,
  }
  let res = await myAxios.put("/team/admin/update", GroupData);
  if (res.data.code === 0) {
    updateGroupFormVisible.value = false
    ElMessage({
      message: '交流群更新成功',
      type: 'success',
    })
    await handleSearch()
  } else {
    ElMessage.error(res.data.description)
  }
}
</script>

<template>
  <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item >首页</el-breadcrumb-item>
    <el-breadcrumb-item>交流群管理</el-breadcrumb-item>
  </el-breadcrumb>
  <el-card>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-input placeholder="请输入群名称" v-model="searchGroupname" clearable @change="handleSearch">
          <template #append>
            <el-button :icon="Search" @click="handleSearch"/>
          </template>
        </el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="addGroupFormVisible = true">添加交流群</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData" table-layout="fixed" border stripe>
      <el-table-column label="图片" width="80px" slot-scope="scope">
        <template #default="scope">
          <el-avatar
              shape="square"
              :src="scope.row.coverImage"
              style="width: 50px;height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="群名称"/>
      <el-table-column prop="description" label="群描述"/>
      <el-table-column prop="maxNum" label="最大人数"/>
      <el-table-column prop="status"  label="类型"/>
      <el-table-column prop="expireTime" label="过期时间"/>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column fixed="right" label="操作" width="120px" slot-scope="scope">
        <template #default="scope">
          <el-button type="primary" :icon="Edit" circle @click="getGroupInfo(scope.row.id)"/>
          <el-button type="danger" :icon="Delete" circle @click="confirmDelete(scope.row.id)"/>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :background="true"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
    />
    <el-dialog v-model="addGroupFormVisible" title="添加交流群" width="40%" center>
      <el-form :model="addTeamData" :rules="addGroupFormRoles">
        <el-form-item label="交流群名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="addTeamData.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth" prop="description">
          <el-input v-model="addTeamData.description" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="最大人数" :label-width="formLabelWidth" prop="maxNum">
          <el-input v-model="addTeamData.maxNum" autocomplete="off"/>
        </el-form-item>

        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-select
              v-model="addTeamData.status"
              placeholder="公开"
              style="width: 240px"
          >
            <el-option
                v-for="item in ValueOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-show="addTeamData.status === '2'" label="群密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="addTeamData.password" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addGroupFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddGroup">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="updateGroupFormVisible" title="更新交流群" width="40%" center>
      <el-form :model="updateGroupForm">
        <el-form-item label="交流群ID" :label-width="formLabelWidth">
          <el-input v-model="updateGroupForm.id" autocomplete="off" disabled/>
        </el-form-item>
        <el-form-item label="交流群名称" :label-width="formLabelWidth">
          <el-input v-model="updateGroupForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="updateGroupForm.description" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="最大人数" :label-width="formLabelWidth">
          <el-input v-model="updateGroupForm.maxNum" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="创建人id" :label-width="formLabelWidth">
          <el-input v-model="updateGroupForm.userId" autocomplete="off" disabled/>
        </el-form-item>
        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-input v-model="updateGroupForm.status" autocomplete="off" disabled/>
        </el-form-item>
        <el-form-item label="过期时间" :label-width="formLabelWidth">
          <div class="block">
            <el-date-picker
                v-model="updateGroupForm.expireTime"
                type="datetime"
                placeholder="请选择一个时间"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="updateGroupFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateGroup">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
    </el-card>
</template>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

.image {
  width: 100%;
  display: block;
}
</style>